package com.alex.megacj;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alex.megacj.handler.ProxyHandler;

@WebServlet(urlPatterns = { "/*" })
public class ProxyServlet extends HttpServlet {
	
	private static final Logger LOGGER = Logger.getLogger(ProxyServlet.class);
	
	private ProxyHandler proxyHandler;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		proxyHandler = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()).getBean(ProxyHandler.class);
		super.init(config);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			proxyHandler.handle(request, response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			response.sendError(500);
		}
	}
}
